import { DataSource } from 'typeorm';
import { dataSourceOptions } from './data-source';

async function fixWorkspaceStatus() {
  console.log('开始修复workspace.status字段...');
  const dataSource = new DataSource(dataSourceOptions);
  await dataSource.initialize();

  try {
    // 检查枚举类型是否存在
    const enumTypeExists = await dataSource.query(`
      SELECT typname FROM pg_type WHERE typname = 'workspace_status_enum'
    `);

    if (enumTypeExists.length === 0) {
      console.log('创建workspace_status_enum枚举类型...');
      await dataSource.query(`
        CREATE TYPE workspace_status_enum AS ENUM ('active', 'inactive', 'deleted');
      `);
    } else {
      console.log('workspace_status_enum枚举类型已存在');
    }

    // 检查status字段是否存在
    const statusFieldExists = await dataSource.query(`
      SELECT column_name 
      FROM information_schema.columns 
      WHERE table_name = 'workspaces' 
      AND column_name = 'status';
    `);

    if (statusFieldExists.length === 0) {
      console.log('向workspaces表添加status字段...');
      await dataSource.query(`
        ALTER TABLE workspaces ADD COLUMN status workspace_status_enum NOT NULL DEFAULT 'active';
      `);
      console.log('status字段已成功添加！');
    } else {
      console.log('status字段已存在');
    }
  } catch (error) {
    console.error('修复过程中发生错误:', error);
  } finally {
    await dataSource.destroy();
    console.log('修复过程完成');
  }
}

// 如果直接运行此文件则执行修复
if (require.main === module) {
  fixWorkspaceStatus()
    .then(() => {
      console.log('修复脚本执行完成');
      process.exit(0);
    })
    .catch(error => {
      console.error('修复脚本执行失败:', error);
      process.exit(1);
    });
}

export { fixWorkspaceStatus }; 